<template>
  <div class="card content-box">
    <el-form ref="ruleFormRef" :rules="rules" :model="addRequestTemplateFormData" style="width: 100%" label-width="122px">
      <el-button type="primary" @click="onSubmitFormPre(ruleFormRef)"> 保存 </el-button>
      <el-button type="primary" @click="backList"> 返回列表 </el-button>
      <el-button type="primary" @click="serviceDir"> 服务目录 </el-button>
      <el-dialog title="选择服务目录" v-model="dialogServiceDirTableVisible">
        <div :style="{ height: '500px' }">
          <el-tree
            :data="serviceSelectList"
            :props="defaultProps"
            :default-expand-all="true"
            @node-click="handleNodeClickService"
            class="custom-tree"
          />
        </div>
      </el-dialog>
      <el-dialog v-model="templateNameDialogVisible" title="内容模板名称" width="30%">
        <el-form style="width: 100%" label-width="120px">
          <el-form-item label="请求内容模板名称 :" prop="etitle">
            <el-input v-model="addRequestTemplateFormData.templateName" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="templateNameBtn(ruleFormRef)">保存</el-button>
          </span>
        </template>
      </el-dialog>
      <div>
        <p>基本信息</p>
      </div>
      <div v-if="showCustomerForm == false">
        <el-row>
          <el-col :span="12">
            <el-form-item class="item" label="所属客户 :" prop="companyName" style="width: 48%">
              <el-input v-model="addRequestTemplateFormData.companyName" @click="dialogCompanyNoTableVisible = true" />
              <el-dialog title="选择客户" v-model="dialogCompanyNoTableVisible">
                <div :style="{ height: '500px' }">
                  <Custemerselect @send-data="sendCompanyNoData" />
                </div>
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="item" label="请求用户 :" prop="createdByName" style="width: 48%">
              <el-input v-model="addRequestTemplateFormData.createdByName" @click="dialogCreatedByTableVisible = true" />
              <el-dialog title="选择用户" v-model="dialogCreatedByTableVisible">
                <div :style="{ height: '500px' }">
                  <Userselect @send-data="sendCreatedByData" :father="fatherValue" />
                </div>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="item" label="请求分类 :" prop="requestCategoryName" style="width: 48%">
              <el-tree-select
                ref="RequestType"
                v-model="requestCategorySelectValue"
                :data="requestCategorySelectList"
                :render-after-expand="false"
                :default-expand-all="true"
                check-strictly
                check-on-click-node
                @change="changeRequestType"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="item" label="标题 :" prop="etitle" style="width: 48%">
              <el-input v-model="addRequestTemplateFormData.etitle" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="item" label="描述 :" style="width: 1200px">
          <WangEditor v-model:value="content" height="400px" />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item class="item" label="来源 :" style="width: 48%">
              <el-tree-select
                v-model="imodeSelectValue"
                :data="imodeSelectList"
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                @change="changeimode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="item" label="优先级 :" style="width: 48%">
              <el-tree-select
                v-model="prioritySelectValue"
                :data="prioritySelectList"
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                @change="changepriority"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="item" label="影响 :" style="width: 48%">
              <el-tree-select
                v-model="effectRangeSelectValue"
                :data="effectRangeSelectList"
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                @change="changeeffectRange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="item" label="复杂程度 :" style="width: 48%">
              <el-tree-select
                v-model="levelSelectValue"
                :data="levelSelectList"
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                @change="changelevel"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="item" label="紧急度 :" style="width: 48%">
              <el-tree-select
                v-model="seriousnessSelectValue"
                :data="seriousnessSelectList"
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                @change="changeseriousness"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="item" label="位置 :" style="width: 48%">
              <el-tree-select
                v-model="LocationSelectValue"
                :data="LocationSelectList"
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                @change="changeLocation"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <div v-if="showCustomerForm == true">
      <form-create v-model="formData" :option="option" :rule="formCreateRules" />
      <el-form style="width: 100%" label-width="122px">
        <el-form-item label="描述 :">
          <WangEditor v-if="edescFlag == true" v-model:value="customerContent" width="1200px" height="400px" ref="cwangEditor" />
        </el-form-item>
      </el-form>
      <form-create v-model="formData" :option="option2" :rule="formCreateRules2" class="custom-tree2" />
    </div>
    <el-dialog title="选择客户" v-model="dialogCustomerCompanyNoTableVisible">
      <div :style="{ height: '500px' }">
        <Custemerselect @send-data="sendCompanyNoDataCustomer" />
      </div>
    </el-dialog>
    <el-dialog title="选择用户" v-model="dialogCustomerCreatedByTableVisible">
      <div :style="{ height: '500px' }">
        <Userselect @send-data="sendCreatedByDataCustomer" :father="fatherValue" />
      </div>
    </el-dialog>

    <el-dialog title="选择请求分类" v-model="dialogRequestCategoryTableVisible">
      <div :style="{ height: '500px' }">
        <el-tree
          :data="requestCategorySelectList"
          :props="defaultProps"
          :default-expand-all="true"
          @node-click="handleNodeClickRequestCategory"
        />
        <el-button class="dialogOkBtn" type="primary" @click="submitRequestCategory" style="min-width: 80px"> 确 定 </el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择位置" v-model="dialogLocationTableVisible">
      <div :style="{ height: '500px' }">
        <el-tree
          :data="LocationSelectList"
          :props="defaultProps"
          :default-expand-all="true"
          @node-click="handleNodeClickLocation"
          class="custom-tree"
        />
        <el-button class="dialogOkBtn" type="primary" @click="submitLocation" style="min-width: 80px"> 确 定 </el-button>
      </div>
    </el-dialog>
    <el-form>
      <el-tabs v-model="activeName">
        <el-tab-pane label="关联配置项" name="first">
          <el-button type="primary" @click="selectCiDialogVisible = true"> 添加 </el-button>
          <el-dialog title="选择关联配置项" v-model="selectCiDialogVisible">
            <div :style="{ height: '500px' }">
              <moreSelectCi @send-data="sendCiData" />
            </div>
          </el-dialog>
          <ProTable
            ref="ciProTable"
            row-key="id"
            :indent="20"
            :data="ciList"
            :columns="ciColumns"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          >
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link @click="deleteci(scope.$index)">删除</el-button>
            </template>
          </ProTable>
        </el-tab-pane>
        <el-tab-pane label="附件" name="second">
          <el-button type="primary" @click="addAttachment"> 添加附件 </el-button>
          <ProTable
            ref="attachmentProTable"
            row-key="id"
            :indent="20"
            :data="attachmentList"
            :columns="attachmentColumns"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          >
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link @click="deleteattachment(scope.$index)">删除</el-button>
            </template>
          </ProTable>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="ts" name="basicForm">
import { ElMessage, FormInstance, FormRules, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, onBeforeUnmount, defineComponent } from "vue";
import { getjggl, emailtest, emailtestexchange, testSMSAccount, getjgglmessage, mergeCompany } from "@/api/modules/jggl";
import Userselect from "@/views/tools/userSelectbyOrgNo/index.vue";
import { isTelOrFax, isEmail } from "@/utils/eleValidate";
import WangEditor from "@/components/WangEditor/index.vue";
import Custemerselect from "@/views/tools/custemerSelect/index.vue";

import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import {
  findPageScheduledTask,
  saveScheduledTask,
  deleteScheduledTask,
  findScheduledTaskById,
  editScheduledTask,
  uploadFile,
  saveRequestTemplate,
  findByTemplateId,
  findCiByIds,
  findFormCustomById
} from "@/api/modules/systemTools";

import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import moreSelectCi from "@/views/tools/moreCiSelect/index.vue";
import ImportExcel from "@/views/tools/uploadFile/index.vue";
import { getCurrentLoginUser } from "@/api/modules/accessController";
import { saveRequest } from "@/api/modules/request";
import formCreate from "@form-create/element-ui"; // 引入 FormCreate
import { Base64 } from "js-base64";
import { useRoute, useRouter } from "vue-router";
import { useTabsStore } from "@/stores/modules/tabs";
const router = useRouter();
const route = useRoute();
const tabStore = useTabsStore();
const content = ref("");

//
// 父组件的值
// const fatherValue = ref({ orgNo: 1 });
const cwangEditor = ref(null);
const dialogCustomerCompanyNoTableVisible = ref(false);
const dialogCustomerCreatedByTableVisible = ref(false); //创建人
const dialogLocationTableVisible = ref(false);
const dialogRequestCategoryTableVisible = ref(false);
const requestCategoryCustomerSelectValue = ref();
const requestCategoryCustomerSelectList = ref<any>([]);
const locationCustomerSelectValue = ref();
const locationCustomerSelectList = ref<any>([]);
const handleNodeClickRequestCategory = (data: any) => {
  console.log(data);
  requestCategoryCustomerSelectValue.value = data;
};
const handleNodeClickLocation = (data: any) => {
  console.log(data);
  locationCustomerSelectValue.value = data;
};
const submitRequestCategory = () => {
  // console.log("sdfaadfds")
  // formData.value["companyName"] ="ss"
  // formData.value["companyNo"] = "ss"
  // console.log(formData.value)
  // formData.value["requestCategoryName"] ="ss"
  // formData.value["requestCategoryNo"] = "ss"
  // console.log(formData.value)
  // console.log("sdfaadfdssssssssssss")
  if (requestCategoryCustomerSelectValue.value == null || requestCategoryCustomerSelectValue.value == undefined) {
    ElMessage.info("请选择请求分类");
    return;
  }
  if ((requestCategoryCustomerSelectValue.value.children as any).length > 0) {
    ElMessage.info("请选择叶子节点");
    return;
  }
  // let tmp=formData.value
  // console.log(tmp)
  // let newParams = JSON.parse(JSON.stringify(tmp));
  // console.log(newParams.requestCategoryName)
  formData.value.requestCategoryName = requestCategoryCustomerSelectValue.value.attr.cname;
  formData.value.requestCategoryNo = requestCategoryCustomerSelectValue.value.attr.id;
  // newParams.requestCategoryName="sd"
  // newParams.requestCategoryNo="dsf"
  // formData.value=newParams
  //失去焦点避免重复打开 对话框
  //let inputBox = document.getElementById("emailTitleTemp") as HTMLInputElement; // 获取输入框元素
  //console.log(inputBox)
  //console.log(cwangEditor.value)
  //inputBox.focus()
  if (cwangEditor.value != null) {
    (cwangEditor.value["editor"] as any).focus();
  }

  dialogRequestCategoryTableVisible.value = false;
};

const submitLocation = () => {
  console.log("sdfaadfds");
  if (locationCustomerSelectValue.value == null || locationCustomerSelectValue.value == undefined) {
    ElMessage.info("请选择位置");
    return;
  }
  console.log("777777777");
  if ((locationCustomerSelectValue.value.children as any).length > 0) {
    ElMessage.info("请选择叶子节点");
    return;
  }
  console.log("8888888888");
  console.log(locationCustomerSelectValue.value);
  formData.value["locationName"] = locationCustomerSelectValue.value.attr.cname;
  formData.value["locationNos"] = locationCustomerSelectValue.value.attr.id;
  //console.log(formData.value)
  //失去焦点避免重复打开 对话框
  // let inputBox = document.getElementById("emailTitleTemp") as HTMLInputElement; // 获取输入框元素
  // inputBox.focus()
  if (cwangEditor.value != null) {
    (cwangEditor.value["editor"] as any).focus();
  }
  dialogLocationTableVisible.value = false;
};
const formData = ref<any>({
  createdByNo: "",
  etitle: "",
  requestCategoryNo: "",
  companyNo: "",
  creator: "",
  approvalNo: "",
  companyName: "",
  createdByName: "",
  requestCategoryName: "",
  imodeNo: "",
  priorityNo: "",
  effectRangeNo: "",
  levelNo: "",
  seriousnessNo: "",
  locationName: "",
  locationNos: ""
});
//客户选择子组件弹窗回调方法
const sendCompanyNoDataCustomer = (data: any) => {
  formData.value["companyName"] = data.orgName;
  formData.value["companyNo"] = data.orgNo;

  //失去焦点避免重复打开 对话框
  // let inputBox = document.getElementById("emailTitleTemp") as HTMLInputElement; // 获取输入框元素
  // inputBox.focus()
  (cwangEditor.value as any).editor.focus();
  dialogCustomerCompanyNoTableVisible.value = false;
};
//用户选择子组件弹窗回调方法
const sendCreatedByDataCustomer = (data: any) => {
  formData.value["createdByNo"] = data.userId;
  formData.value["createdByName"] = data.fullName;
  //失去焦点避免重复打开 对话框
  // let inputBox = document.getElementById("emailTitleTemp") as HTMLInputElement; // 获取输入框元素
  // inputBox.focus()
  (cwangEditor.value as any).editor.focus();
  dialogCustomerCreatedByTableVisible.value = false;
};
const edescFlag = ref(false);
const formCreateRules = ref<any>([]);
const formCreateRules2 = ref<any>([]);
const option = ref({
  submitBtn: false
});
const option2 = ref({
  submitBtn: false
});
const customerContent = ref("");
//

const UserselectRef = ref<InstanceType<typeof Userselect> | null>(null);
const defaultProps = {
  children: "children",
  label: "data"
};
const showCustomerForm = ref(false);
const handleNodeClickService = (data: Tree) => {
  ElMessageBox.confirm("您输入的数据将不会被保存，确定切换表单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      dialogServiceDirTableVisible.value = false;
      console.log(data);
      addRequestTemplateFormData.serviceDirIds = data.attr.id;
      if (data.attr.formId != null && data.attr.formId != undefined) {
        addRequestTemplateFormData.formId = data.attr.formId;
        showCustomerForm.value = true;
        findFormCustomById(data.attr.formId).then(res => {
          edescFlag.value = false;
          let newParams = JSON.parse(JSON.stringify(res));
          let yyde = Base64.decode(newParams.formCustomContents); //解密
          console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          let formCreateRules2Array: any[] = [];

          for (let i = 0; i < a.length; i++) {
            if (a[i].title == "所属客户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCompanyNoTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求分类") {
              a[i]["on"] = {
                focus(inject) {
                  dialogRequestCategoryTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求用户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCreatedByTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "位置") {
              a[i]["on"] = {
                focus(inject) {
                  dialogLocationTableVisible.value = true;
                }
              };
            }
            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined) {
              let optionList = [];
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i].options.push({ label: element["dname"], value: element["dcode"] });
                });
              });
            }

            if (a[i].title == "描述") {
              edescFlag.value = true;
              continue;
            }
            if (edescFlag.value == false) {
              formCreateRulesArray.push(a[i] as any);
            } else {
              formCreateRules2Array.push(a[i] as any);
            }
          }
          formCreateRules.value = formCreateRulesArray;
          formCreateRules2.value = formCreateRules2Array;
        });
      } else {
        addRequestTemplateFormData.formId = "";
        showCustomerForm.value = false;
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作"
      });
    });
};
const templateNameDialogVisible = ref(false);
const templateNameBtn = async (formEl: FormInstance | undefined) => {
  if (addRequestTemplateFormData.templateName == "") {
    ElMessage({
      type: "error",
      message: "模板名称不能为空"
    });
    return;
  }
  onSubmitForm(formEl);
  templateNameDialogVisible.value = false;
};

//关联配置项开始
const ciProTable = ref<ProTableInstance>();
const ciList = ref<any>([]);

const selectCiDialogVisible = ref(false);
const ciColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "cino", label: "固定资产编号", sortable: true },
  { prop: "ciname", label: "名称", sortable: true, width: 260 },
  { prop: "categoryName", label: "分类", sortable: true, width: 260 },
  { prop: "status", label: "状态", sortable: true, width: 260 },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);

// 删除
const deleteci = async (index: any) => {
  ciList.value.splice(index, 1);
};

//选中资产子组件弹窗回调方法
const sendCiData = (data: [resCIList]) => {
  if (data.length > 0) {
    for (let i = 0; i < data.length; i++) {
      //去重
      let addflag = true;
      ciList.value.forEach(val => {
        if (val.ciId == data[i].ciId) {
          addflag = false;
        }
      });
      if (addflag == true) {
        ciList.value.push(data[i]);
      } else {
        ElMessage({
          type: "info",
          message: "存在相同配置 :   " + data[i]["ciname"] + "，  已自动过滤重复配置"
        });
      }
    }
  }
  selectCiDialogVisible.value = false;
};
export interface resCIList {
  ciname: string;
  cino: string;
  categoryName: string;
  categoryNo: string;
  status: string;
  ciId: number;
  attachmentStr: string;
  fileName: string;
  beginTime: string;
  companyName: string;
  companyNo: number;
  contractName: string;
  contractNo: number;
  dataFlag: number;
  description: string;
  dialect: string;
  endTime: string;
  finishTime: number;
  flagName: string;
  lastUpdater: string;
  packageName: string;
  respondTime: number;
  ruleName: string;
  ruleNo: number;
  rulePackageNo: number;
  salience: number;
  showFinishTime: string;
  showRespondTime: string;
  beforeOrAfter: boolean;
  beforeOrAfterStr: string;
  timeStr: string;
}
//关联配置项结束

//附件开始
const attachmentProTable = ref<ProTableInstance>();
const attachmentList = ref<any>([]);
const attachmentColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "fileName", label: "文件名称" },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);
const uploadFileRes = async (param: any) => {
  let res = JSON.parse(JSON.stringify(param));
  let attachmentStr = res.fileName + "==" + res.msg + "==" + res.fileSize + "-s-";
  let attachment = {
    fileName: res.fileName,
    attachmentStr: attachmentStr
  };
  attachmentList.value.push(attachment);
};
// 添加附件
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const addAttachment = () => {
  const params = {
    title: "",
    tempApi: uploadFile,
    importApi: uploadFile,
    getTableList: ciProTable.value?.getTableList,
    addAttachmentMethod: uploadFileRes
  };
  dialogRef.value?.acceptParams(params);
};
// 删除附件
const deleteattachment = async (index: any) => {
  attachmentList.value.splice(index, 1);
};
//附件结束

//开始
//请求客户
const dialogCompanyNoTableVisible = ref(false);
const dialogCreatedByTableVisible = ref(false); //创建人
const requestCategorySelectValue = ref();
const requestCategorySelectList = ref<any>([]);
//来源选择开始
const imodeSelectValue = ref();
const imodeSelectList = ref<any>([]);
const changeimode = (val: any) => {
  imodeSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTemplateFormData.imodeNo = newElement.dcode;
    }
  });
};
//来源选择结束
//优先级选择开始
const prioritySelectValue = ref();
const prioritySelectList = ref<any>([]);
const changepriority = (val: any) => {
  prioritySelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTemplateFormData.priorityNo = newElement.dcode;
    }
  });
};
//优先级选择结束
//影响选择开始
const effectRangeSelectValue = ref();
const effectRangeSelectList = ref<any>([]);
const changeeffectRange = (val: any) => {
  effectRangeSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTemplateFormData.effectRangeNo = newElement.dcode;
    }
  });
};
//影响结束
//复杂程度选择开始
const levelSelectValue = ref();
const levelSelectList = ref<any>([]);
const changelevel = (val: any) => {
  levelSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTemplateFormData.levelNo = newElement.dcode;
    }
  });
};
//紧急度选择开始
const seriousnessSelectValue = ref();
const seriousnessSelectList = ref<any>([]);
const changeseriousness = (val: any) => {
  seriousnessSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTemplateFormData.seriousnessNo = newElement.dcode;
    }
  });
};
//紧急度结束
//紧急度选择开始
const LocationSelectValue = ref();
const LocationSelectList = ref<any>([]);
const changeLocation = (val: any) => {
  if (val == "所在位置") {
    ElMessage.info("当前节点不可选");
    LocationSelectValue.value = addRequestTemplateFormData.locationName;
    return;
  }
  traverseTree(LocationSelectList.value[0], node => {
    if (node.value == val.toString()) {
      addRequestTemplateFormData.locationNos = node.attr.id;
      addRequestTemplateFormData.locationName = node.attr.cname;
    }
  });
};
// 父组件的值
const fatherValue = ref({ orgNo: 1 });

const addRequestTemplateFormData = reactive({
  isShowBorder: 0,
  isNewForm: true,
  // technicianName:"",
  creator: "",
  actionName: "新增",
  approvalNo: 0,
  serviceDirIds: "",
  reportId: 0,
  scheduledTaskId: "",
  scheduledTaskType: "request",
  beanId: "autoUpdateRequestJob",
  companyNo: 1,
  etitle: "",
  templateType: "request",

  formId: "",
  companyName: "",
  // companyNo:1,
  createdByName: "",
  createdByNo: "",
  requestCategoryName: "",
  requestCategoryNo: "",
  edesc: "",
  imodeNo: "",
  priorityNo: "",
  effectRangeNo: "",
  levelNo: "",
  seriousnessNo: "",
  locationName: "",
  locationNos: "",
  attachmentStr: "",
  templateName: "",
  templateId: ""
});

//客户选择子组件弹窗回调方法
const sendCompanyNoData = (data: any) => {
  dialogCompanyNoTableVisible.value = false;
  addRequestTemplateFormData.companyNo = data.orgNo;
  addRequestTemplateFormData.companyName = data.orgName;
  fatherValue.value.orgNo = data.orgNo;
};
//用户选择子组件弹窗回调方法
const sendCreatedByData = (data: any) => {
  console.log(data);
  dialogCreatedByTableVisible.value = false;
  addRequestTemplateFormData.createdByNo = data.userId;
  addRequestTemplateFormData.createdByName = data.fullName;
  // addRequestTemplateFormData.technicianName=data.loginName;
  addRequestTemplateFormData.creator = data.loginName;
};
// ProTable 实例

//请求分类选择
const changeRequestType = (val: any) => {
  traverseTree(requestCategorySelectList.value[0], node => {
    if (node.value == val.toString()) {
      if ((node.children as any).length > 0) {
        // console.log("非叶子节点")
        ElMessage.info("请选择叶子节点");
        requestCategorySelectValue.value = addRequestTemplateFormData.requestCategoryName;
      } else {
        addRequestTemplateFormData.requestCategoryNo = node.attr.id;
        addRequestTemplateFormData.requestCategoryName = node.attr.cname;
        addRequestTemplateFormData.etitle = node.attr.cname;
      }
    }
  });
  console.log(val);
};

const onSubmitFormPre = async (formEl: FormInstance | undefined) => {
  templateNameDialogVisible.value = true;
};
const onSubmitForm = async (formEl: FormInstance | undefined) => {
  let idsStr = "";
  for (let i = 0; i < ciList.value.length; i++) {
    if (idsStr == "") {
      idsStr = "?cinos=" + ciList.value[i].ciId;
    } else {
      idsStr = idsStr + "&cinos=" + ciList.value[i].ciId;
    }
  }
  let attachmentStr = "";
  for (let i = 0; i < attachmentList.value.length; i++) {
    if (attachmentStr == "") {
      attachmentStr = attachmentList.value[i].attachmentStr;
    } else {
      attachmentStr += attachmentList.value[i].attachmentStr;
    }
  }
  addRequestTemplateFormData.attachmentStr = attachmentStr;

  if (showCustomerForm.value == true) {
    console.log(formData.value);
    if (customerContent.value == null || customerContent.value == "") {
      ElMessage.error("描述不能为空");
      return;
    }
    addRequestTemplateFormData.edesc = customerContent.value.toString();
    if (formData.value.companyNo == null || formData.value.companyNo == "") {
      ElMessage.error("请选择所属客户");
      return;
    }
    if (formData.value.createdByNo == null || formData.value.createdByNo == "") {
      ElMessage.error("请选择用户");
      return;
    }
    if (formData.value.etitle == null || formData.value.etitle == "") {
      ElMessage.error("标题不能为空");
      return;
    }
    if (formData.value.requestCategoryNo == null || formData.value.requestCategoryNo == "") {
      ElMessage.error("分类不能为空");
      return;
    }

    //数据拷贝
    Object.keys(formData.value).forEach(key => {
      addRequestTemplateFormData[`${key}`] = `${formData.value[key]}`;
    });

    //校验成功
    saveRequestTemplate(addRequestTemplateFormData, "requestDTO", idsStr).then(res => {
      console.log(res);
      ElMessage.success("新增成功");
      tabStore.removeTabs(route.fullPath);
      router.push(`/system/tools/contentTemplateManagement?pageNo=${Math.random().toFixed(3)}`);
    });
    ElMessage.success("保存成功");
    console.log(addRequestTemplateFormData);
  } else {
    if (content.value == null || content.value == "") {
      ElMessage.error("描述不能为空");
      return;
    }
    addRequestTemplateFormData.edesc = content.value.toString();

    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        //校验成功
        saveRequestTemplate(addRequestTemplateFormData, "requestDTO", idsStr).then(res => {
          console.log(res);
          ElMessage.success("新增成功");
          tabStore.removeTabs(route.fullPath);
          router.push(`/system/tools/contentTemplateManagement?pageNo=${Math.random().toFixed(3)}`);
        });
        ElMessage.success("保存成功");
      } else {
        ElMessage.error("请正确填写表单");
      }
    });
  }
};
// 返回列表
const backList = async () => {
  tabStore.removeTabs(route.fullPath);
  router.push(`/system/tools/contentTemplateManagement?pageNo=${Math.random().toFixed(3)}`);
};
const dialogServiceDirTableVisible = ref(false);
// 服务目录
const serviceDir = async () => {
  dialogServiceDirTableVisible.value = true;
  // tabStore.removeTabs(route.fullPath);
  // router.push(`/system/tools/regularTaskManagement?pageNo=${Math.random().toFixed(3)}`);
};

//结束

const ruleFormRef = ref<FormInstance>();
const activeName = ref("first");

const rules = reactive<FormRules>({
  companyName: [{ required: true, message: "请选择公司", trigger: "blur" }],
  createdByName: [{ required: true, message: "请选择请求用户", trigger: "blur" }],
  requestCategoryName: [{ required: true, message: "请选择请求分类", trigger: "blur" }],
  etitle: [{ required: true, message: "请输入标题", trigger: "blur" }],
  edesc: [{ required: true, message: "请输入描述", trigger: "blur" }]
});
const serviceSelectList = ref<any>([]);
onMounted(() => {
  //加载公司信息
  getjgglmessage().then(res => {
    let newParams = JSON.parse(JSON.stringify(res));
    addRequestTemplateFormData.companyName = newParams.companyName;
    addRequestTemplateFormData.companyNo = newParams.companyNo == 0 ? 1 : newParams.companyNo;
  });
  //加载用户数据
  getCurrentLoginUser().then(res => {
    let newRes = JSON.parse(JSON.stringify(res));
    addRequestTemplateFormData.createdByNo = newRes.userId;
    addRequestTemplateFormData.createdByName = newRes.fullName;
    // addRequestTemplateFormData.technicianName=newRes.loginName;
    addRequestTemplateFormData.creator = newRes.loginName;
  });
  //请求分类选择树
  getCategoryTreeAllData("Request").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    let k: any[] = [];
    k.push(res);
    requestCategorySelectList.value = k;
  });
  //来源
  dataDictionaryItemsfindByCode("imode").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    imodeSelectList.value = res as any;
  });
  //优先级priority
  dataDictionaryItemsfindByCode("priority").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    prioritySelectList.value = res as any;
  });
  //影响effectRange
  dataDictionaryItemsfindByCode("effectRange").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    effectRangeSelectList.value = res as any;
  });
  dataDictionaryItemsfindByCode("level").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    levelSelectList.value = res as any;
  });
  dataDictionaryItemsfindByCode("seriousness").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    seriousnessSelectList.value = res as any;
  });
  //位置
  getCategoryTreeAllData("Location").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    LocationSelectList.value = [res as any];
    //LocationCustomerSelectList.value = [res as any];
  });
  getCategoryTreeAllData("Service").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    serviceSelectList.value = [res as any];
  });
  //编辑时加载数据
  let query = JSON.parse(JSON.stringify(route.query));
  // findByTemplateId findCiByIds
  if (query.id != undefined) {
    findByTemplateId({ templateId: query.id }, "templateDTO", []).then(res => {
      let newParams = JSON.parse(JSON.stringify(res));
      let ciIds = "";
      for (let i = 0; i < newParams.dto.relatedCiNos.length; i++) {
        if (ciIds == "") {
          ciIds = "?ids=" + newParams.dto.relatedCiNos[i];
        } else {
          ciIds += "&ids=" + newParams.dto.relatedCiNos[i];
        }
      }
      findCiByIds(ciIds).then(ciRes => {
        if (ciRes != null) {
          (ciRes as any).forEach(function (element) {
            ciList.value.push(element);
          });
        }
      });
      let valArr = newParams.dto.attachmentStr.split("-s-");
      for (let i = 0; i < valArr.length; i++) {
        if (valArr[i] == "") {
          continue;
        }
        let attObj = valArr[i].split("==");
        let attachment = {
          fileName: attObj[0],
          attachmentStr: valArr[i] + "-s-"
        };
        attachmentList.value.push(attachment);
      }

      // 	addRequestTemplateFormData.technicianName= newParams.dto.technicianName==undefined?"":newParams.dto.technicianName;
      // addRequestTemplateFormData.technicianNo= newParams.dto.technicianNo==undefined?"":newParams.dto.technicianNo;
      addRequestTemplateFormData.creator = newParams.dto.creator == undefined ? "" : newParams.dto.creator;
      // addRequestTemplateFormData.actionName= newParams.dto.actionName==undefined?"":newParams.dto.actionName;
      addRequestTemplateFormData.approvalNo = newParams.dto.approvalNo == undefined ? "" : newParams.dto.approvalNo;
      addRequestTemplateFormData.serviceDirIds = newParams.serviceDirIds == undefined ? "" : newParams.serviceDirIds;
      addRequestTemplateFormData.reportId = newParams.dto.reportId == undefined ? "" : newParams.dto.reportId;
      addRequestTemplateFormData.scheduledTaskId =
        newParams.dto.scheduledTaskId == undefined ? "" : newParams.dto.scheduledTaskId;
      addRequestTemplateFormData.scheduledTaskType =
        newParams.dto.scheduledTaskType == undefined ? "" : newParams.dto.scheduledTaskType;
      // addRequestTemplateFormData.beanId= newParams.dto.beanId==undefined?"":newParams.dto.beanId;

      addRequestTemplateFormData.etitle = newParams.dto.etitle == undefined ? "" : newParams.dto.etitle;
      addRequestTemplateFormData.templateType = newParams.templateType == undefined ? "" : newParams.templateType;

      addRequestTemplateFormData.formId = newParams.formId == undefined ? "" : newParams.formId;
      addRequestTemplateFormData.companyName = newParams.dto.companyName == undefined ? "" : newParams.dto.companyName;
      addRequestTemplateFormData.companyNo = newParams.dto.companyNo == undefined ? 1 : newParams.dto.companyNo;
      addRequestTemplateFormData.createdByName = newParams.dto.createdByName == undefined ? "" : newParams.dto.createdByName;
      addRequestTemplateFormData.createdByNo = newParams.dto.createdByNo == undefined ? "" : newParams.dto.createdByNo;
      addRequestTemplateFormData.requestCategoryName =
        newParams.dto.requestCategoryName == undefined ? "" : newParams.dto.requestCategoryName;
      addRequestTemplateFormData.requestCategoryNo =
        newParams.dto.requestCategoryNo == undefined ? "" : newParams.dto.requestCategoryNo;
      requestCategorySelectValue.value = newParams.dto.requestCategoryName == undefined ? "" : newParams.dto.requestCategoryName;
      addRequestTemplateFormData.edesc = newParams.dto.edesc == undefined ? "" : newParams.dto.edesc;
      content.value = newParams.dto.edesc == undefined ? "" : newParams.dto.edesc;
      // imodeSelectValue prioritySelectValue effectRangeSelectValue levelSelectValue seriousnessSelectValue LocationSelectValue
      addRequestTemplateFormData.imodeNo = newParams.dto.imodeNo == undefined ? "" : newParams.dto.imodeNo;
      addRequestTemplateFormData.priorityNo = newParams.dto.priorityNo == undefined ? "" : newParams.dto.priorityNo;
      addRequestTemplateFormData.effectRangeNo = newParams.dto.effectRangeNo == undefined ? "" : newParams.dto.effectRangeNo;
      addRequestTemplateFormData.levelNo = newParams.dto.levelNo == undefined ? "" : newParams.dto.levelNo;
      addRequestTemplateFormData.seriousnessNo = newParams.dto.seriousnessNo == undefined ? "" : newParams.dto.seriousnessNo;
      addRequestTemplateFormData.locationName = newParams.dto.locationName == undefined ? "" : newParams.dto.locationName;
      addRequestTemplateFormData.locationNos = newParams.dto.locationNos == undefined ? "" : newParams.dto.locationNos;
      imodeSelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addRequestTemplateFormData.imodeNo) {
          imodeSelectValue.value = newElement.value;
        }
      });
      prioritySelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addRequestTemplateFormData.priorityNo) {
          prioritySelectValue.value = newElement.value;
        }
      });
      effectRangeSelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addRequestTemplateFormData.effectRangeNo) {
          effectRangeSelectValue.value = newElement.value;
        }
      });
      levelSelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addRequestTemplateFormData.levelNo) {
          levelSelectValue.value = newElement.value;
        }
      });
      seriousnessSelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addRequestTemplateFormData.seriousnessNo) {
          seriousnessSelectValue.value = newElement.value;
        }
      });
      LocationSelectValue.value = newParams.dto.locationName == undefined ? "" : newParams.dto.locationName;
      addRequestTemplateFormData.attachmentStr = newParams.dto.attachmentStr == undefined ? "" : newParams.dto.attachmentStr;
      addRequestTemplateFormData.templateName = newParams.templateName == undefined ? "" : newParams.templateName;
      addRequestTemplateFormData.templateId = newParams.templateId == undefined ? "" : newParams.templateId;
      console.log("newParams.formId!=undefined");
      console.log(newParams.formId != undefined);
      //自定义表单回显数据
      if (newParams.formId != undefined && newParams.formId != 0) {
        showCustomerForm.value = true;
        findFormCustomById(newParams.formId).then(resFindFormCustom => {
          edescFlag.value = false;
          let newResFindFormCustom = JSON.parse(JSON.stringify(resFindFormCustom));
          let yyde = Base64.decode(newResFindFormCustom.formCustomContents); //解密
          console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          let formCreateRules2Array: any[] = [];

          for (let i = 0; i < a.length; i++) {
            if (a[i].title == "所属客户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCompanyNoTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求分类") {
              a[i]["on"] = {
                focus(inject) {
                  dialogRequestCategoryTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求用户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCreatedByTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "位置") {
              a[i]["on"] = {
                focus(inject) {
                  dialogLocationTableVisible.value = true;
                }
              };
            }
            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined) {
              let optionList = [];
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i].options.push({ label: element["dname"], value: element["dcode"] });
                });
              });
            }

            if (a[i].title == "描述") {
              edescFlag.value = true;
              continue;
            }
            if (edescFlag.value == false) {
              formCreateRulesArray.push(a[i] as any);
            } else {
              formCreateRules2Array.push(a[i] as any);
            }
          }
          formCreateRules.value = formCreateRulesArray;
          formCreateRules2.value = formCreateRules2Array;

          let attrVals = newParams.dto.attrVals == undefined ? {} : newParams.dto.attrVals;
          setTimeout(() => {
            formData.value.creator = newParams.dto.creator == undefined ? "" : newParams.dto.creator;
            // addRequestTemplateFormData.actionName= newParams.dto.actionName==undefined?"":newParams.dto.actionName;
            formData.value.approvalNo = newParams.dto.approvalNo == undefined ? "" : newParams.dto.approvalNo;
            //addRequestTemplateFormData.serviceDirIds= newParams.serviceDirIds==undefined?"":newParams.serviceDirIds;
            //addRequestTemplateFormData.reportId= newParams.dto.reportId==undefined?"":newParams.dto.reportId;
            //addRequestTemplateFormData.scheduledTaskId= newParams.dto.scheduledTaskId==undefined?"":newParams.dto.scheduledTaskId;
            //addRequestTemplateFormData.scheduledTaskType= newParams.dto.scheduledTaskType==undefined?"":newParams.dto.scheduledTaskType;
            // addRequestTemplateFormData.beanId= newParams.dto.beanId==undefined?"":newParams.dto.beanId;

            formData.value.etitle = newParams.dto.etitle == undefined ? "" : newParams.dto.etitle;
            //addRequestTemplateFormData.templateType= newParams.templateType==undefined?"":newParams.templateType;

            //addRequestTemplateFormData.formId= newParams.formId==undefined?"":newParams.formId;
            formData.value.companyName = newParams.dto.companyName == undefined ? "" : newParams.dto.companyName;
            formData.value.companyNo = newParams.dto.companyNo == undefined ? 1 : newParams.dto.companyNo;
            formData.value.createdByName = newParams.dto.createdByName == undefined ? "" : newParams.dto.createdByName;
            formData.value.createdByNo = newParams.dto.createdByNo == undefined ? "" : newParams.dto.createdByNo;
            formData.value.requestCategoryName =
              newParams.dto.requestCategoryName == undefined ? "" : newParams.dto.requestCategoryName;
            formData.value.requestCategoryNo =
              newParams.dto.requestCategoryNo == undefined ? "" : newParams.dto.requestCategoryNo;
            //requestCategorySelectValue.value=newParams.dto.requestCategoryName==undefined?"":newParams.dto.requestCategoryName;
            //addRequestTemplateFormData.edesc= newParams.dto.edesc==undefined?"":newParams.dto.edesc;
            customerContent.value = newParams.dto.edesc == undefined ? "" : newParams.dto.edesc;
            // imodeSelectValue prioritySelectValue effectRangeSelectValue levelSelectValue seriousnessSelectValue LocationSelectValue
            formData.value.imodeNo = newParams.dto.imodeNo == undefined ? "" : newParams.dto.imodeNo;
            formData.value.priorityNo = newParams.dto.priorityNo == undefined ? "" : newParams.dto.priorityNo;
            formData.value.effectRangeNo = newParams.dto.effectRangeNo == undefined ? "" : newParams.dto.effectRangeNo;
            formData.value.levelNo = newParams.dto.levelNo == undefined ? "" : newParams.dto.levelNo;
            formData.value.seriousnessNo = newParams.dto.seriousnessNo == undefined ? "" : newParams.dto.seriousnessNo;
            formData.value.locationName = newParams.dto.locationName == undefined ? "" : newParams.dto.locationName;
            formData.value.locationNos = newParams.dto.locationNos == undefined ? "" : newParams.dto.locationNos;
            Object.keys(attrVals).forEach(key => {
              Object.keys(formData.value).forEach(key2 => {
                if (`${key}` == `${key2}`) {
                  if (`${attrVals[key]}` == "true") {
                    formData.value[`${key2}`] = true;
                  } else {
                    formData.value[`${key2}`] = `${attrVals[key]}`;
                  }
                }
              });
            });
          }, 1500);
        });
      }
    });
  }
});
interface Tree {
  label: string;
  children?: Tree[];
  attr: any;
}
interface TreeNode {
  value: any;
  lable: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
</script>

<style scoped lang="scss">
@import "./index.scss";
.item {
  width: 500px;
}
.custom-tree {
  height: 450px; /* 你想要的高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}
.custom-tree2 {
  height: 200px; /* 你想要的高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}
</style>
